package com.hllxd.hism.passport.login.gateway.config.mvc;

//import com.hualala.hllxd.passport.service.util.BuriedPoint;
//import com.hualala.hllxd.passport.service.util.ConsoleContext;
//import com.hualala.hllxd.passport.service.util.ThreadLocalManager;
//import com.hualala.hllxd.passport.service.util.TraceUtil;
import com.hllxd.hism.passport.login.gateway.util.BuriedPoint;
import com.hllxd.hism.passport.login.gateway.util.ThreadLocalManager;
import com.hllxd.hism.passport.login.gateway.util.ConsoleContext;
import com.hllxd.hism.passport.login.gateway.util.TraceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class AtomicInterceptor extends HandlerInterceptorAdapter {

    public static boolean setConsoleContext(HttpServletRequest request) {
        try {
            ConsoleContext context = new ConsoleContext();
            context.setRequest(request);
            context.setBeginMs(System.currentTimeMillis());
            String traceId = request.getHeader("traceID");
            if(traceId==null) {
                context.setTraceId(TraceUtil.newTraceId());
            }else {
                context.setTraceId(traceId);
            }
            // user holder
//            log.info("set context success.");
            ThreadLocalManager.setConsoleContext(context);
        } catch (Exception e) {
            log.warn("error in preHandle getUser. url is:"+request.getRequestURL(), e);
            return false;
        }
        return true;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //log.info("request header: {}", JSON.toJSONString(request.getHeaderNames()));
        if(! setConsoleContext(request)) {
            log.warn("set local content failed.");
            return false;
        }
        return super.preHandle(request, response, handler);
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        BuriedPoint.write(response, request.getRequestURI());
        ThreadLocalManager.clear();
        super.postHandle(request, response, handler, modelAndView);
    }
}
